﻿using AutoMapper;
using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interfance;
using B.S.BasicData.Read.Apilication.Common.User;
using B.S.BasicData.Read.DTOS;

using Humanizer;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.S.BasicData.Read.Apilication.Handler.User
{
    public class GetUserHandler : IRequestHandler<GetUserCommon, ApiPaimg<UserDTO>>
    {
        private readonly IBaseRepository<UserModel> userrepo;
        private readonly IBaseRepository<ProvinceModel> provinceRepo;
        private readonly IBaseRepository<RoleModel> roleRepo;
        private readonly IBaseRepository<AccountRoleModel> accountroleModel;
        private readonly IMapper mapper;

        public GetUserHandler(IBaseRepository<UserModel> userrepo,IBaseRepository<ProvinceModel> provinceRepo,
            IBaseRepository<RoleModel> roleRepo,
            IBaseRepository<AccountRoleModel> accountroleModel,IMapper mapper)
        {
            this.userrepo = userrepo;
            this.provinceRepo = provinceRepo;
            this.roleRepo = roleRepo;
            this.accountroleModel = accountroleModel;
            this.mapper = mapper;
        }

      
        public  Task<ApiPaimg<UserDTO>> Handle(GetUserCommon request, CancellationToken cancellationToken)
        {
            ApiPaimg<UserDTO> res = new ApiPaimg<UserDTO>();
            var user = userrepo.GetAll().Where(x => x.IsDel == false);
            var province = provinceRepo.GetAll();
            var role = roleRepo.GetAll();
            var accountrole = accountroleModel.GetAll();

            var rusult = mapper.Map<List<UserDTO>>(user);

            foreach (var item in rusult)
            {
                item.provinceName =  provinceRepo.GetAll().FirstOrDefault(x=>x.provinceId==item.provinceId).provinceName;
                var userRoleIquery = accountroleModel.GetAll().Where(x =>x.UserId == item.UserId);
                var RoleIquery = roleRepo.GetAll().Where(x => x.IsDeleted == false);
                var IQueryables = (from a in userRoleIquery
                                   join b in RoleIquery on a.RoleId equals b.RoleId
                                   select new {a,b}).ToList();
                List<string> rolenameList = IQueryables.Select(x=>x.b.RoleName).ToList();
                item.RoleName=string.Join(",", rolenameList);
            }

            res.ToTaCount = rusult.Count();
            res.ToTaPage = (int)Math.Ceiling(res.ToTaCount * 1.0 / request.PageSize);
            res.Message = "分页查询成功";
            res.PageData = rusult.OrderByDescending(x => x.UserId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
            return Task.FromResult(res);
        }
    }
}
